<template>
  <div class="admin-manage-container">
    <el-card class="admin-manage-card">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="搜索">
            <el-input
              v-model="searchForm.keyword"
              placeholder="用户名/手机号/邮箱"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <!-- <el-form-item label="角色">
            <el-select v-model="searchForm.role" placeholder="选择角色" clearable>
              <el-option label="超级管理员" value="super_admin" />
              <el-option label="管理员" value="admin" />
              <el-option label="运营人员" value="operator" />
            </el-select>
          </el-form-item> -->
          <el-form-item label="状态">
            <el-select
              class="status-search"
              v-model="searchForm.status"
              placeholder="选择状态"
              clearable
            >
              <el-option label="全部" value="all" />
              <el-option label="正常" value="active" />
              <el-option label="禁用" value="inactive" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
            <el-button type="success" @click="handleAdd">添加管理员</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 管理员列表 -->
      <el-table v-loading="loading" :data="adminList" style="width: 100%" border>
        <el-table-column label="管理员信息" min-width="200">
          <template #default="{ row }">
            <div class="admin-info">
              <el-avatar :size="40" :src="row.avatar">
                {{ row.nickname?.charAt(0) || row.username.charAt(0) }}
              </el-avatar>
              <div class="info-detail">
                <div class="username">{{ row.username }}</div>
                <div class="nickname" v-if="row.nickname">{{ row.nickname }}</div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="手机号" width="120">
          <template #default="{ row }">
            {{ row.phone || '空' }}
          </template>
        </el-table-column>
        <el-table-column label="邮箱" width="180">
          <template #default="{ row }">
            {{ row.email || '空' }}
          </template>
        </el-table-column>

        <!-- <el-table-column label="角色" width="120">
          <template #default="{ row }">
            <el-tag :type="getRoleTagType(row.role)">
              {{ getRoleLabel(row.role) }}
            </el-tag>
          </template>
        </el-table-column> -->

        <el-table-column label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'danger'">
              {{ row.is_active ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="last_login" label="最后登录" width="180" />
        <el-table-column prop="created_at" label="创建时间" width="180" />

        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)"> 编辑 </el-button>
            <el-button type="warning" link @click="handleResetPassword(row)"> 重置密码 </el-button>
            <el-button
              :type="row.is_active ? 'danger' : 'success'"
              link
              @click="handleToggleStatus(row)"
            >
              {{ row.is_active ? '禁用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 编辑对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑管理员' : '添加管理员'"
        width="500px"
      >
        <el-form ref="formRef" :model="editForm" :rules="rules" label-width="100px">
          <template v-if="!isEdit">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="editForm.username" />
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="editForm.password" type="password" show-password />
            </el-form-item>
          </template>

          <template v-if="isEdit">
            <el-form-item label="头像" class="avatar-item">
              <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :auto-upload="false"
                :on-change="handleAvatarChange"
                :before-upload="beforeUpload"
                :limit="1"
              >
                <img v-if="editForm.avatar" :src="editForm.avatar" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </template>

          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="editForm.nickname" />
          </el-form-item>

          <el-form-item label="手机号" prop="phone">
            <el-input v-model="editForm.phone" />
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email" />
          </el-form-item>

          <!-- <el-form-item label="角色" prop="role">
            <el-select v-model="editForm.role">
              <el-option label="超级管理员" value="super_admin" />
              <el-option label="管理员" value="admin" />
              <el-option label="运营人员" value="operator" />
            </el-select>
          </el-form-item> -->

          <!-- <el-form-item label="权限" prop="permissions">
            <el-checkbox-group v-model="editForm.permissions">
              <el-checkbox label="user_manage">用户管理</el-checkbox>
              <el-checkbox label="order_manage">订单管理</el-checkbox>
              <el-checkbox label="photographer_manage">摄影师管理</el-checkbox>
              <el-checkbox label="portfolio_manage">作品管理</el-checkbox>
              <el-checkbox label="system_manage">系统管理</el-checkbox>
            </el-checkbox-group>
          </el-form-item> -->
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSave" :loading="saveLoading"> 保存 </el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import type { Customer, CustomerQuery, CustomerUpdateDto } from '@/types/customer'
import {
  getAdmins,
  updateCustomerStatus,
  updateCustomerInfo,
  createAdmin,
  resetAdminPassword,
} from '@/api/user'
import { v4 as uuidv4 } from 'uuid'
import type { FileItem, UploadFile } from '@/types/upload'
import { uploadAvatarWithUserId } from '@/api/upload'
import type { CreateAdminDto } from '@/types/admin'
import { encryptPassword } from '@/utils/encrypt'
import { beforeUpload } from '@/utils/upload'

// 模拟数据
const adminList = ref<Customer[]>([])

// 搜索表单
const searchForm = reactive<CustomerQuery>({
  keyword: '',
  status: 'all',
  page: 1,
  pageSize: 10,
})

const singleFile = reactive<FileItem>({
  uid: '',
  name: '',
  status: 'ready',
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 加载状态
const loading = ref(false)
const saveLoading = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref<FormInstance>()

// 编辑表单
const editForm = reactive<CustomerUpdateDto & { username: string; password: string }>({
  id: 0,
  username: '',
  password: '',
  nickname: '',
  phone: '',
  email: '',
  avatar: '',
})

// 表单验证规则
const rules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 4, max: 20, message: '长度在 4 到 20 字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
  ],
  phone: [
    { required: false, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' },
  ],
  email: [
    { required: false, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
  ],
  // role: [{ required: true, message: '请选择角色', trigger: 'change' }],
  // permissions: [{ required: true, type: 'array', message: '请选择权限', trigger: 'change' }],
})

// 获取角色标签类型
// const getRoleTagType = (role: AdminRole) => {
//   const types: Record<AdminRole, string> = {
//     super_admin: 'danger',
//     admin: 'warning',
//     operator: 'info',
//   }
//   return types[role]
// }

// 获取角色标签文本
// const getRoleLabel = (role: AdminRole) => {
//   const labels: Record<AdminRole, string> = {
//     super_admin: '超级管理员',
//     admin: '管理员',
//     operator: '运营人员',
//   }
//   return labels[role]
// }

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = ''
  searchForm.status = 'all'
  handleSearch()
}

// 处理分页
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchData()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchData()
}

// 添加管理员
const handleAdd = () => {
  isEdit.value = false
  Object.assign(editForm, {
    username: '',
    password: '',
    nickname: '',
    phone: '',
    email: '',
    avatar: '',
  })
  dialogVisible.value = true
}

// 处理头像上传
const handleAvatarChange = (file: UploadFile) => {
  if (!beforeUpload(file.raw)) return

  // 创建预览URL
  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onload = async () => {
    Object.assign(singleFile, {
      uid: uuidv4(),
      name: file.name,
      url: reader.result as string,
      status: 'ready',
      raw: file.raw,
    })

    try {
      if (!singleFile.raw) {
        ElMessage.error('请选择文件')
        return
      }

      singleFile.status = 'uploading'
      singleFile.percentage = 0

      const response = await uploadAvatarWithUserId(singleFile.raw, editForm.id, (percentage) => {
        singleFile.percentage = percentage
      })

      singleFile.status = 'success'
      editForm.avatar = response.data.data.url
      ElMessage.success('上传成功')
    } catch (error) {
      singleFile.status = 'error'
      ElMessage.error('上传失败')
    }
  }
}

// 编辑管理员
const handleEdit = (row: Customer) => {
  isEdit.value = true
  Object.assign(editForm, {
    id: row.id,
    username: row.username,
    nickname: row.nickname,
    email: row.email,
    phone: row.phone,
    avatar: row.avatar,
  })
  dialogVisible.value = true
}

// 重置密码
const handleResetPassword = async (row: Customer) => {
  try {
    await ElMessageBox.confirm(`确定要重置 ${row.username} 的密码吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    await resetAdminPassword(row.id)
    ElMessage.success('密码已重置')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('重置密码失败')
    }
  }
}

// 切换状态
const handleToggleStatus = async (row: Customer) => {
  try {
    await ElMessageBox.confirm(`确定要${row.is_active ? '禁用' : '启用'}该用户吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    await updateCustomerStatus(row.id)
    ElMessage.success('操作成功')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

// 保存
const handleSave = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      saveLoading.value = true
      if (isEdit.value) {
        try {
          const { id, username, ...updateData } = editForm
          await updateCustomerInfo(id, updateData)
          ElMessage.success('保存成功')
          dialogVisible.value = false
          fetchData()
        } catch (error) {
          ElMessage.error('保存失败')
        } finally {
          saveLoading.value = false
        }
      } else {
        try {
          const createData: CreateAdminDto = {
            username: editForm.username,
            password: encryptPassword(editForm.password),
            nickname: editForm.nickname,
            phone: editForm.phone || undefined,
            email: editForm.email || undefined,
            role: 2,
          }
          await createAdmin(createData)
          ElMessage.success('创建管理员成功')
          dialogVisible.value = false
          fetchData()
        } catch (error) {
          ElMessage.error('创建管理员失败')
        } finally {
          saveLoading.value = false
        }
      }
    }
  })
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const { data } = await getAdmins({
      keyword: searchForm.keyword,
      status: searchForm.status,
      page: currentPage.value,
      pageSize: pageSize.value,
    })
    adminList.value = data.data.items
    total.value = data.data.meta.total
  } catch (error) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.admin-manage-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
  min-height: calc(100vh - 200px);
  box-sizing: border-box;
}

.admin-manage-card {
  margin-top: 0;
}

.search-bar {
  margin-bottom: 20px;
}

.admin-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.info-detail {
  display: flex;
  flex-direction: column;
}

.username {
  font-weight: bold;
}

.nickname {
  font-size: 12px;
  color: #666;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.status-search {
  width: 100px;
}
</style>
